package com.innovation.chengzhangriji.ui;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.DataResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.ui.model.UIHistoryPhoto;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseHistoryPhotoAndVideoActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener {

    protected TextView textEmptyView;
    protected RecyclerView recyclerView;

    // 默认拉去 50 条视频日记
    protected final int PAGE_SIZE = 50;

    // 最后的lastTs
    protected long lastTs = System.currentTimeMillis();

    // 日记
    protected List<Discover> models = new ArrayList<>();
    // 视频时间线
    protected List<UIHistoryPhoto> photos = new ArrayList<>();

    // 数据适配器
    protected RecyclerView.Adapter<RecyclerView.ViewHolder> adapter;

    protected CuteToolbar toolbar;

    protected Baby mBaby;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_video);
        mBaby = DatabaseManager.getInstance(this).queryBaby(Config.getLoginInfo(this).getBabyID());
        if(mBaby == null) {
            tipShow("宝宝不存在");
            finish();
            return;
        }
        // 初始化视图
        setupLayout();
    }

    // 初始化视图
    protected void setupLayout() {

        toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setCuteTitle(getCuteTitle());
        toolbar.setOnClickCuteToolbarListener(this);
        textEmptyView = (TextView) findViewById(R.id.empty_view);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = getAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new PullUpListener());
        // 加载本地数据
        models.addAll(DatabaseManager.getInstance(this).getLocalDiscover(mLoginInfo.getBabyID(), getType(), System.currentTimeMillis(), PAGE_SIZE));
        setupData();
        // 请求网络数据
        requestHistory();
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {

    }

    // 更新本地的日记
    protected void insertOrReplaceInTxDiscover(int babyID, DataResponse data) {
        // 日记信息
        for (int i = 0; i < data.getData().length; i++) {
            Discover discover = new Discover();
            discover.setDiaryID(data.getData()[i].getUuid());
            discover.setIsDelete(data.getData()[i].getState() == 0);
            if(discover.getIsDelete()) {
                // 删除本地日记
                DatabaseManager.getInstance(this).deleteDiscover(discover.getDiaryID());
            } else {
                discover.setAudio(data.getData()[i].getAudioUrl());
                discover.setVideo(data.getData()[i].getVideoUrl());
                discover.setDuration(data.getData()[i].getLength());
                discover.setGrowthStageID(data.getData()[i].getBabyState());
                discover.setUserID(data.getData()[i].getUserID());
                discover.setMemberName(data.getData()[i].getRole());
                discover.setType(data.getData()[i].getType());
                discover.setMilestone(data.getData()[i].getMilestone());
                discover.setScreenshot(data.getData()[i].getScreenshotUrl());
                discover.setTheme(data.getData()[i].getTheme());
                discover.setText(data.getData()[i].getText());
                discover.setAudio(data.getData()[i].getAudioUrl());
                discover.setBabyID(babyID);
                discover.setDiaryFrom(1); // 来自日记本
                discover.setUserHeadUrl(data.getData()[i].getUserHeadUrl());
                discover.setCreateTS(data.getData()[i].getCreateTS());
                // 更新本地日记
                DatabaseManager.getInstance(this).insertOrReplaceDiscover(discover, data.getData()[i].getPhotoUrls());
            }
        }
    }

    // 加载更多
    protected void loadMore() {
        if(isEnd) {
            tipShow("没有更多"+ getCuteTitle() +"了");
            return;
        }
        if(models.size() > 0 && models.get(models.size() - 1) != null) {
            isLoadMode = true;
            lastTs = models.get(models.size() - 1).getCreateTS();
            // 加载本地视频
            List<Discover> discoverList = DatabaseManager.getInstance(BaseHistoryPhotoAndVideoActivity.this).getLocalDiscover(mLoginInfo.getBabyID(), getType(), lastTs, PAGE_SIZE);
            if(discoverList == null || discoverList.size() == 0) {
                requestHistory();
            } else {
                models.addAll(discoverList);
                setupData();
                isLoadMode = false;
            }
        }
    }

    // 加载更多
    protected boolean isLoadMode = false;
    protected boolean isEnd = false;

    // 请求网络，加载历史
    protected void requestHistory() {
        Client.requestHistory(this, mLoginInfo.getPhone(), mLoginInfo.getToken().getAccessToken(), mLoginInfo.getBabyID(), lastTs, PAGE_SIZE, getType(), new ResponseHandler() {
            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                DataResponse dataResponse = get(value.toString(), DataResponse.class);
                if (dataResponse == null || dataResponse.getData() == null || dataResponse.getData().length == 0) {
                    tipShow("没有更多" + getCuteTitle() + "了");
                    if (photos.size() == 0) {
                        textEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        textEmptyView.setVisibility(View.GONE);
                    }
                    isEnd = true;
                    return;
                }
                insertOrReplaceInTxDiscover(mLoginInfo.getBabyID(), dataResponse);
                // 刷新本地数据
                if (isLoadMode) {
                    isLoadMode = false;
                    List<Discover> discoverList = DatabaseManager.getInstance(BaseHistoryPhotoAndVideoActivity.this).getLocalDiscover(mLoginInfo.getBabyID(), getType(), lastTs, PAGE_SIZE);
                    if (discoverList == null || discoverList.size() == 0) {
                        tipShow("没有更多"+ getCuteTitle() +"了");
                        isEnd = true;
                        return;
                    }
                    // 加载本地数据
                    models.addAll(discoverList);
                } else {
                    photos.clear();
                    models.clear();
                    // 加载本地数据
                    models.addAll(DatabaseManager.getInstance(BaseHistoryPhotoAndVideoActivity.this).getLocalDiscover(mLoginInfo.getBabyID(), getType(), System.currentTimeMillis(), PAGE_SIZE));
                }
                setupData();
                if (photos.size() == 0) {
                    textEmptyView.setVisibility(View.VISIBLE);
                } else {
                    textEmptyView.setVisibility(View.GONE);
                }
            }
        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                tipShow(getString(R.string.tip_network_unavailable));
                if (photos.size() == 0) {
                    textEmptyView.setVisibility(View.VISIBLE);
                } else {
                    textEmptyView.setVisibility(View.GONE);
                }
            }
        });
    }

    // 下拉加载更多
    class PullUpListener extends RecyclerView.OnScrollListener {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if(!isLoadMode && layoutManager.findLastVisibleItemPosition() == photos.size() - 1) {
                loadMore();
            }
        }
    }

    protected abstract String getCuteTitle();

    protected abstract void setupData();

    protected abstract int getType();

    protected abstract RecyclerView.Adapter<RecyclerView.ViewHolder> getAdapter();
}
